<template>
  <view class="page">
    <view class="page-container">
      <!-- 页面头部 -->
      <view class="page-header">
        <!-- Logo -->
        <view class="logo">🚗</view>
        <!-- 页面标题 -->
        <view class="page-title">注册账号</view>
        <view class="page-subtitle">创建您的汽车管理账户</view>
      </view>

      <!-- 注册表单 -->
      <view class="form fade-in">
        <!-- 手机号输入 -->
        <view class="form-item">
          <label class="form-label">手机号</label>
          <input
            class="form-input"
            type="number"
            placeholder="作为登录账号"
            maxlength="11"
            v-model="formData.phone"
            :class="{ error: errors.phone }"
          />
          <view v-if="errors.phone" class="error-message">{{
            errors.phone
          }}</view>
        </view>

        <!-- 验证码输入 -->
        <view class="form-item">
          <label class="form-label">验证码</label>
          <view class="verification-group">
            <input
              class="form-input verification-input"
              type="number"
              placeholder="请输入"
              maxlength="6"
              v-model="formData.verificationCode"
              :class="{ error: errors.verificationCode }"
            />
            <button
              class="verification-btn"
              :disabled="!canSendSms || smsCountdown > 0"
              @tap="sendVerificationCode"
            >
              {{ smsCountdown > 0 ? `${smsCountdown}s` : "获取验证码" }}
            </button>
          </view>
          <view v-if="errors.verificationCode" class="error-message">{{
            errors.verificationCode
          }}</view>
        </view>

        <!-- 密码输入 -->
        <view class="form-item">
          <label class="form-label">设置密码</label>
          <input
            class="form-input"
            type="password"
            placeholder="6-20位字符"
            v-model="formData.password"
            :class="{ error: errors.password }"
          />
          <view v-if="errors.password" class="error-message">{{
            errors.password
          }}</view>
        </view>

        <!-- 确认密码输入 -->
        <view class="form-item">
          <label class="form-label">确认密码</label>
          <input
            class="form-input"
            type="password"
            placeholder="再次输入密码"
            v-model="formData.confirmPassword"
            :class="{ error: errors.confirmPassword }"
          />
          <view v-if="errors.confirmPassword" class="error-message">{{
            errors.confirmPassword
          }}</view>
        </view>

        <!-- 用户协议 -->
        <view class="agreement">
          <checkbox
            class="agreement-checkbox"
            :checked="formData.agreeProtocol"
            @change="handleProtocolChange"
          />
          <text class="agreement-text">
            点击"下一步"按钮即表示您同意并遵守
            <text class="agreement-link" @tap="showProtocol"
              >《用户授信协议》</text
            >
          </text>
        </view>

        <!-- 注册按钮 -->
        <button
          class="btn btn-primary"
          :disabled="!canSubmit"
          @tap="handleRegister"
        >
          {{ isLoading ? "注册中..." : "下一步" }}
        </button>

        <!-- 登录链接 -->
        <view class="action-links">
          <text class="action-link" @tap="goToLogin">已有账号？立即登录</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { authApi } from '@/utils/api.js'
import { validate } from '@/utils/common.js'

/**
 * 页面标题
 */
const pageTitle = '注册账号'

/**
 * 表单数据
 */
const formData = ref({
  phone: '',              // 手机号
  verificationCode: '',   // 验证码
  password: '',           // 密码
  confirmPassword: '',    // 确认密码
  agreeProtocol: false    // 是否同意协议
})

/**
 * 表单错误信息
 */
const errors = ref({
  phone: '',
  verificationCode: '',
  password: '',
  confirmPassword: ''
})

/**
 * 加载状态
 */
const isLoading = ref(false)

/**
 * 短信倒计时
 */
const smsCountdown = ref(0)

/**
 * 是否可以发送短信
 */
const canSendSms = computed(() => {
  return validate.phone(formData.value.phone) && smsCountdown.value === 0
})

/**
 * 是否可以提交表单
 */
const canSubmit = computed(() => {
  return formData.value.phone &&
    formData.value.verificationCode &&
    formData.value.password &&
    formData.value.confirmPassword &&
    formData.value.agreeProtocol &&
    !isLoading.value
})

/**
 * 处理用户协议状态变化
 */
function handleProtocolChange (event) {
  formData.value.agreeProtocol = event.detail.value.length > 0
}

/**
 * 表单验证
 */
function validateForm () {
  const newErrors = {}

  // 验证手机号
  if (!formData.value.phone) {
    newErrors.phone = '请输入手机号'
  } else if (!validate.phone(formData.value.phone)) {
    newErrors.phone = '请输入正确的手机号'
  }

  // 验证验证码
  if (!formData.value.verificationCode) {
    newErrors.verificationCode = '请输入验证码'
  } else if (formData.value.verificationCode.length !== 6) {
    newErrors.verificationCode = '验证码为6位数字'
  }

  // 验证密码
  if (!formData.value.password) {
    newErrors.password = '请输入密码'
  } else if (formData.value.password.length < 6) {
    newErrors.password = '密码长度不能少于6位'
  } else if (formData.value.password.length > 20) {
    newErrors.password = '密码长度不能超过20位'
  }

  // 验证确认密码
  if (!formData.value.confirmPassword) {
    newErrors.confirmPassword = '请再次输入密码'
  } else if (formData.value.password !== formData.value.confirmPassword) {
    newErrors.confirmPassword = '两次输入的密码不一致'
  }

  errors.value = newErrors
  return Object.keys(newErrors).length === 0
}

/**
 * 发送验证码
 */
async function sendVerificationCode () {
  if (!canSendSms.value) {
    return
  }

  try {
    // 调用发送验证码API
    await authApi.sendSmsCode({
      phone: formData.value.phone,
      type: 'register'
    })

    uni.showToast({
      title: '验证码已发送',
      icon: 'success'
    })

    // 开始倒计时
    startSmsCountdown()

  } catch (error) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: '发送失败，请重试',
      icon: 'none'
    })
  }
}

/**
 * 开始短信倒计时
 */
function startSmsCountdown () {
  smsCountdown.value = 60
  const timer = setInterval(() => {
    smsCountdown.value--
    if (smsCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

/**
 * 处理注册
 */
async function handleRegister () {
  // 表单验证
  if (!validateForm()) {
    return
  }

  // 检查是否同意协议
  if (!formData.value.agreeProtocol) {
    uni.showToast({
      title: '请先同意用户协议',
      icon: 'none'
    })
    return
  }

  isLoading.value = true

  try {
    // 调用注册API
    await authApi.register({
      phone: formData.value.phone,
      verificationCode: formData.value.verificationCode,
      password: formData.value.password
    })

    uni.showToast({
      title: '注册成功',
      icon: 'success'
    })

    // 跳转到登录页面
    setTimeout(() => {
      uni.redirectTo({
        url: '/pages/login/login'
      })
    }, 1500)

  } catch (error) {
    console.error('注册失败:', error)
    uni.showToast({
      title: '注册失败，请重试',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

/**
 * 跳转到登录页面
 */
function goToLogin () {
  uni.navigateBack()
}

/**
 * 显示用户协议
 */
function showProtocol () {
  uni.showModal({
    title: '用户授信协议',
    content: '这里是用户授信协议的内容...',
    showCancel: false
  })
}
</script>

<style scoped>
/* 页面特定样式 */

/* 验证码组合输入框 */
.verification-group {
  display: flex;
  gap: var(--spacing-base);
}

.verification-input {
  flex: 1;
}

.verification-btn {
  width: 200rpx;
  height: 88rpx;
  background-color: var(--primary-color);
  color: #ffffff;
  border: none;
  border-radius: var(--border-radius);
  font-size: var(--font-size-base);
  font-weight: 500;
  transition: all 0.3s ease;
}

.verification-btn:active {
  background-color: var(--primary-hover);
}

.verification-btn:disabled {
  background-color: var(--bg-tertiary);
  color: var(--text-muted);
}

/* 错误消息样式 */
.error-message {
  color: var(--danger-color);
  font-size: var(--font-size-sm);
  margin-top: var(--spacing-xs);
  padding-left: var(--spacing-sm);
}

.form-input.error {
  border-color: var(--danger-color);
}

/* 协议区域样式 */
.agreement {
  margin: var(--spacing-xl) 0;
  padding: 0 var(--spacing-sm);
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-sm);
}

.agreement-text {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  line-height: 1.6;
  flex: 1;
}

.agreement-link {
  color: var(--primary-color);
}

/* 按钮禁用状态 */
.btn:disabled {
  background-color: var(--bg-tertiary) !important;
  color: var(--text-muted) !important;
  cursor: not-allowed;
}

/* 操作链接样式 */
.action-links {
  margin-top: var(--spacing-xl);
  text-align: center;
}

.action-link {
  color: var(--primary-color);
  font-size: var(--font-size-base);
  text-decoration: none;
}

.action-link:active {
  color: var(--primary-hover);
}

/* 响应式适配 */
@media screen and (max-width: 750px) {
  .verification-btn {
    width: 160rpx;
    font-size: var(--font-size-sm);
  }

  .page-header {
    padding: var(--spacing-xl) 0;
  }

  .logo {
    width: 100rpx;
    height: 100rpx;
    font-size: 40rpx;
  }
}
</style>